package com.wzz.controller;

import cn.hutool.core.bean.BeanUtil;
import com.wzz.es.IndentEs;
import com.wzz.pojo.Indent;
import com.wzz.service.IndentEsService;
import com.wzz.service.IndentService;
import com.wzz.vo.PageInfoVo;
import com.wzz.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author DarkClown
 * @date 2024-08-12 17:25
 * @project_name day0812-month
 * @parem
 **/
@RequestMapping("/user/es")
@RestController
public class EsController {
    @Autowired
    IndentEsService indentEsService;
    @Autowired
    IndentService indentService;



    @RequestMapping("/esList")
    private R esList(@RequestBody PageInfoVo pageInfoVo){
        return indentEsService.selectEs(pageInfoVo);
    }

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @RequestMapping("innit")
    private R innit(){
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(IndentEs.class);

        if (indexOps.exists()){
            indexOps.delete();
        }

        indexOps.create();
        Document mapping = indexOps.createMapping();
        indexOps.putMapping(mapping);


        List<Indent> list = indentService.selectList1();

        for (Indent indent : list) {
            IndentEs indentEs = BeanUtil.toBean(indent, IndentEs.class);
            elasticsearchRestTemplate.save(indentEs);
        }



        return R.OK("初始化成功");
    }

    @Scheduled(cron = "0 0/2 * * * ?")
    public void synDate(){
        List<Indent> list = indentService.selectList();

        for (Indent indent : list) {
            IndentEs indentEs = BeanUtil.toBean(indent, IndentEs.class);
            elasticsearchRestTemplate.save(indentEs);
        }
    }

}
